package com.yunxin.core.domain.service.order.impl;


import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.yunxin.common.utils.JacksonUtils;
import com.yunxin.core.application.service.ProductQueryGatewayService;
import com.yunxin.core.domain.model.order.OrderUserApply;
import com.yunxin.core.domain.model.order.OrderUserApplyDetail;
import com.yunxin.core.domain.service.order.OrderUserApplyQWService;
import com.yunxin.core.dto.ApiConfigWecom;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@DS("core")
@Slf4j
@Component
@RequiredArgsConstructor
public class OrderUserApplyQWServiceImpl implements OrderUserApplyQWService {

    private final ProductQueryGatewayService productQueryGatewayService;

    private final RedisTemplate redisTemplate;
    private final String CONNECT_STR = "&";
    private final String LINK_STR = "=";
    private final String CUSTOMER_ID = "customerId";



    /**
     * 获取场景连接
     *
     * @param userApply
     * @param productId
     */
    @Override
    public String getWxWorkUrl(OrderUserApply userApply, Long productId,String clientIp) {
        //根据产品id获取企微配置信息
        try {
            ApiConfigWecom config = productQueryGatewayService.getWeComApiConfig(productId);
            log.info("本次处理的企业微信产品id为:{}",productId);
            log.info("本次处理的企业微信的customerId为:{}",userApply.getId());

            if (Objects.isNull(config)) return null;
            String result = HttpUtil.get(config.getServiceUrl() + config.getScenes() + CONNECT_STR + CUSTOMER_ID + LINK_STR + userApply.getId());
            JSONObject object = new JSONObject(result);
            log.info("响应码为 ： {}", object.getInt("code"));
            log.info("响应消息 ： {}", object.getStr("msg"));
            String url = object.getStr("data");
            log.info("微信跳转链接为 ： {}", url);

            //将关键信息存储到redis
            Map<String, String> dataObj = Map.of("applyOrderNo", userApply.getApplyOrderNo(),"productId",productId.toString(),"ip",clientIp,"phone",userApply.getUserPhone(),"name",userApply.getUserName());
            String format = JacksonUtils.X.format(dataObj);
            //超时时间
            redisTemplate.opsForValue().set(String.valueOf(userApply.getId()),format,5, TimeUnit.MINUTES);
            return url;
        } catch (Exception e) {
            log.info("获取场景连接失败：{}",e);
            return null;
        }
    }
}


























